package com.ellfors.module_first.index_rcv

import android.view.LayoutInflater
import android.view.ViewGroup
import com.ellfors.common.base.adapter.BaseSingleAdapter
import com.ellfors.common.ext.dp2px
import com.ellfors.module_first.databinding.ItemIndexRcvContentBinding

class IndexRcvAdapter :
    BaseSingleAdapter<CountryBean, ItemIndexRcvContentBinding>() {

    private var mSelectedCountry: CountryBean? = null

    override val initViewBinding: (LayoutInflater, ViewGroup, Boolean) -> ItemIndexRcvContentBinding
        get() = ItemIndexRcvContentBinding::inflate

    override fun convert(
        holder: SingleViewHolder<ItemIndexRcvContentBinding>, position: Int, item: CountryBean?
    ) {
        holder.binding.tvContent.apply {
            text = item?.country ?: ""
            isSelected = item?.country == mSelectedCountry?.country
            layoutParams = buildViewMarginBottom(this.layoutParams, position)
        }
    }

    private fun buildViewMarginBottom(
        layoutParams: ViewGroup.LayoutParams, position: Int
    ): ViewGroup.MarginLayoutParams {
        val params = layoutParams as ViewGroup.MarginLayoutParams
        //不是最后一条
        if (position < items.size - 1) {
            //判断是否与下一条分组相同
            params.bottomMargin =
                if (items[position].suspensionTag != items[position + 1].suspensionTag) {
                    12.dp2px()
                } else {
                    0
                }
        } else {
            //否则没有下间距
            params.bottomMargin = 0
        }
        return params
    }

    fun setSelectedCountry(bean: CountryBean) {
        mSelectedCountry = bean
        notifyItemRangeChanged(0, items.size)
    }
}